package com.psg.controller;

import com.psg.pojo.Produce;
import com.psg.service.ProduceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/produce")
public class ProduceController {

    @Autowired
    private ProduceService produceService;


    @RequestMapping("/toProductMessage")
    private String toProductMessage(){
        return "shop_message";
    }

    @RequestMapping("/shop_message")
    private String toShopMessage(){
        return "shop_message";
    }

    @RequestMapping("/toReadmoreShop")
    private String totoReadmoreShop(){
        return "readmoreShop";
    }

    @RequestMapping("/message")
    public ModelAndView message(@RequestParam(value = "id") Integer id,ModelAndView mav,HttpServletRequest request){
        Produce produce = produceService.selectProduce(id);
        mav.addObject("produce",produce);
        request.getSession().setAttribute("produce",produce);
        mav.setViewName("shop_message");
        return mav;
    }
    @RequestMapping("/classify")
    public String classify(@RequestParam("classify")String classify,
                           HttpServletRequest request){
        List<Produce> produceList = produceService.classify(classify);
        request.setAttribute("products",produceList);
        return "readmoreShop";
    }

    @RequestMapping("/showMore")
    public String showMore(@RequestParam("category") Integer category,
                           HttpServletRequest request){
        List<Produce> produceList = produceService.findByCategory(category);
        request.setAttribute("products",produceList);
        return "readmoreShop";
    }

    @RequestMapping("/shorts")
    public String shorts(HttpServletRequest request){
        List<Produce> produceList=(List<Produce>)request.getSession().getAttribute("products");
        Collections.sort(produceList);
        request.setAttribute("products",produceList);
        return "readmoreShop";
    }

    @RequestMapping("/search")
    public ModelAndView search(String searchText,ModelAndView mav){
        if (StringUtils.isBlank(searchText)) {
            mav.setViewName("redirect:/");
            return mav;
        }
        List<Produce> produceList = produceService.searchProduces(searchText);
        mav.addObject("productList",produceList);
        mav.setViewName("searchLike");
        return mav;
    }


}
